package com.hougong.lineclient.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.hougong.lineclient.common.Constants;
import com.hougong.lineclient.common.GlobalCode;
import com.hougong.lineclient.common.GlobalData;
import com.hougong.lineclient.entity.MyFriendVo;
import com.hougong.lineclient.entity.PersonMessageVo;
import com.hougong.lineclient.request.LoginRequest;
import com.hougong.lineclient.transport.ClientConfig;
import com.hougong.lineclient.utils.DateUtils;
import com.hougong.lineclient.utils.HttpClientUtils;
import com.hougong.lineclient.utils.SendUtils;
import com.hougong.lineclient.view.BootView;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
public class BootController {
    public static final Logger LOGGER = LoggerFactory.getLogger(BootController.class);
    @Autowired
    private BootView bootView;


    public void bootMenu() {
        bootView.bootMenu();
        bootView.xinhaoFill("输入菜单id:(1,2,3):");
        Scanner scanner = new Scanner(System.in);
        String menuId = scanner.nextLine();
        switch (menuId) {
            case "1":
                login();
                break;
            case "2":
                register();
                break;
            case "3":
                exit();
                break;
            default:
                bootMenu();
                break;
        }
    }

    public void start() {
        try {
            ClientConfig.getInstance().connectToServer();
        } catch (InterruptedException e) {
            System.out.println("连接服务器失败....");
        }
        if(ClientConfig.channel!=null){
            bootMenu();
        }else {
            System.out.print("输入新的服务器ip地址:");
            Scanner scanner=new Scanner(System.in);
            String newHost = scanner.nextLine();
            Constants.host=newHost;
            start();
        }
    }

    private void exit() {
        System.exit(0);
    }

    private void register() {
        System.out.println("设置用户名:");
        Scanner scanner=new Scanner(System.in);
        String userName = scanner.nextLine();
        System.out.println("设置密码:");
        String password = scanner.nextLine();
        System.out.println("设置昵称:");
        String nickname=scanner.nextLine();
        System.out.println("您的手机号:");
        String phone=scanner.nextLine();

        boolean b = registerRequest(userName, password, nickname, phone);
        if(b){
            System.out.println("(●—●)注册成功！！");
            bootMenu();
        }else {
            register();
        }
    }

    private void login() {
        bootView.xinhaoFill("输入账号,姓名(逗号隔开):");
        try {
            String s = new Scanner(System.in).nextLine();
            String[] split = s.split(",", 2);
            String userName = split[0];
            String password = split[1];
            LoginRequest loginRequest = new LoginRequest();
            loginRequest.setPassword(password);
            loginRequest.setPasswordLen((short) password.getBytes().length);
            loginRequest.setUserName(userName);
            loginRequest.setUserNameLen((short) userName.getBytes().length);
            GlobalData.inputUserName = userName;
            GlobalData.inputPassword = password;
            SendUtils.sendRequest(GlobalCode.Client_Login.getBizCode(), loginRequest);
            return;
        } catch (Exception e) {
            LOGGER.error("------ error! -----", e.getMessage());
            login();
        }
    }

    public String getHttpPath() {
        return "http://" + Constants.host + ":" + Constants.httpPort;
    }

    public Map<String, Object> preGenParams() {
        HashMap<String, Object> params = new HashMap<>();
        params.put("token", GlobalData.token);
        return params;
    }

    public boolean isOk(JSONObject jsonObject) {
        int code = jsonObject.getInteger("code");
        if (code == 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 进入好友列表+群列表 主界面
     */
    public void mainViewListAction() {
        ArrayList<MyFriendVo> myfriendList = getMyFriendListRequest();
        bootView.friendList(myfriendList);
        JSONArray myGroupListRequest = getMyGroupListRequest();
        bootView.groupListView(myGroupListRequest);
        waitOperate();
    }



    /**
     * 等待操作  增加好友或者进入好友聊天
     *
     * @return
     */
    public void waitOperate() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                bootView.xinhaoFill("addf 命令添加好友(addf 用户名):");
                bootView.xinhaoFill(("chatf 命令进入和好友聊天(chatf 好友id)"));
                bootView.xinhaoFill("lookfa 命令查看好友申请通知");
                bootView.xinhaoFill("chatg 命令进入群聊天(chatg 群id)");
                Scanner scanner = new Scanner(System.in);
                String input = scanner.nextLine();
                if(input!=null){
                    input=input.trim();
                    if(input.startsWith("chatf")){
                        String fid=input.replaceFirst("chatf ","").trim();
                        if (GlobalData.mapMyFriend.get(Long.valueOf(fid)) == null) {
                            bootView.xinhaoFill("好友id不存在!");
                            mainViewListAction();
                        }else {
                            intoFriendChat(GlobalData.mapMyFriend.get(Long.valueOf(fid)));
                        }
                    }else if(input.startsWith("addf")){
                        String fusername=input.replaceFirst("addf","").trim();
                        if(StringUtils.isBlank(fusername)){
                            System.out.println("没有输入好友用户名");
                        }else{
                            addFriend(fusername);
                        }
                        mainViewListAction();
                    }else if(input.startsWith("lookfa")){
                        //进入查看好友申请
                        getFriendApply();
                    }else if(input.startsWith("chatg")){
                        String gid=input.replaceFirst("chatg ","").trim();
                        if (GlobalData.mapGroup.get(Long.valueOf(gid)) == null) {
                            bootView.xinhaoFill("群id不存在!");
                            mainViewListAction();
                        }else {
                            intoGroupChat(GlobalData.mapGroup.get(Long.valueOf(gid)));
                        }
                    }

                    else {
                        mainViewListAction();
                    }
                }else {
                    waitOperate();
                }
            }
        }).start();

    }


    public void getFriendApply(){
        JSONObject applyFriendHistory = getApplyFriendHistory();
        if(applyFriendHistory==null){
            mainViewListAction();
        }else{
            bootView.applyFriendListView(applyFriendHistory.getJSONArray("myapplyaddfriendlist"));
            String input=new Scanner(System.in).nextLine();
            if(input.startsWith("accept")){
                String accept = input.replaceFirst("accept", "").trim();
                if(StringUtils.isNotBlank(accept)){
                    applyOrRejectFriend(Long.valueOf(accept),1);
                }
                getFriendApply();
            }else if(input.startsWith("reject")){
                String reject = input.replaceFirst("reject", "").trim();
                if(StringUtils.isNotBlank(reject)){
                    applyOrRejectFriend(Long.valueOf(reject),0);
                }
                getFriendApply();
            }else if("_fuck".equals(input)){
                mainViewListAction();
            }else{
                getFriendApply();
            }
        }
    }


    /**
     * 进入好友聊天面板
     *
     * @param friendVo
     */
    public void intoFriendChat(MyFriendVo friendVo) {
        String fUsername = friendVo.getUsername();
        bootView.xinhaoFill("正在和(" + fUsername + ")聊天");
        bootView.xinhaoFill("                              ");
        ArrayList<PersonMessageVo> friendChatMessageList = getFriendChatMessageListRequest(friendVo.getUid());
        bootView.friendChatView(fUsername, friendChatMessageList);
        GlobalData.friend = friendVo;
        sendFriendMessage(friendVo.getUid());
    }

    public void intoGroupChat(JSONObject jsonObject){
        Long gid = jsonObject.getLong("groupId");
        GlobalData.gid=gid;
        String groupRemark = jsonObject.getString("groupRemark");
        bootView.xinhaoFill("正在群("+groupRemark+")里聊天");
        bootView.xinhaoFill("                              ");
        JSONObject gm = getGroupHistoryMessageRequest(GlobalData.gid);
        bootView.groupChatView(gm.getJSONArray("groupMessageList"));
        sendGroupMessage(gid);
    }

    public void sendGroupMessage(Long gid) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Scanner scanner = new Scanner(System.in);
                while (true) {
                    System.out.println("输入你说的话,'_fuck'返回上一级:");
                    String message = scanner.nextLine();
                    if (org.apache.commons.lang.StringUtils.isNotBlank(message)) {
                        if ("_fuck".equals(message)) {
                            break;
                        } else {
                            String url = getHttpPath() + "/message/send_group_message";
                            Map<String, Object> map = preGenParams();
                            map.put("gid", gid);
                            map.put("message", message);
                            String s = HttpClientUtils.sendPost(url, map);
                            JSONObject result = JSONObject.parseObject(s);
                            if (isOk(result)) {
                              //  System.out.println("你说 : " + message + "      " + DateUtils.formatDateTime(new Date()));
                            } else {
                                System.out.println(result.get("msg"));
                            }
                        }
                    }
                }
                mainViewListAction();
            }
        }).start();


    }


    public  JSONObject getGroupHistoryMessageRequest(Long gid){
        String url=getHttpPath()+"/message/get_history_group_message";
        Map<String, Object> map = preGenParams();
        map.put("gid",gid);
        String s = HttpClientUtils.sendPost(url, map);
        JSONObject result = JSONObject.parseObject(s);
        if(isOk(result)){
            System.out.println("操作成功");
            return result;
        }else {
            System.out.println(result.get("msg"));
            return null;
        }
    }




    public void applyOrRejectFriend(long id,int type){
        String url = getHttpPath() + "/apply/acceptoreject";
        Map<String, Object> map = preGenParams();
        map.put("operatype",type);
        map.put("applyaddfriendid",id);
        String s = HttpClientUtils.sendPost(url, map);
        JSONObject result = JSONObject.parseObject(s);
        if(isOk(result)){
            System.out.println("操作成功");
        }else {
            System.out.println(result.get("msg"));
        }
    }


    public void sendFriendMessage(Long fid) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Scanner scanner = new Scanner(System.in);
                while (true) {
                    System.out.println("输入你说的话,'_fuck'返回上一级:");
                    String message = scanner.nextLine();
                    if (org.apache.commons.lang.StringUtils.isNotBlank(message)) {
                        if ("_fuck".equals(message)) {
                            break;
                        } else {
                            String url = getHttpPath() + "/message/send_friend_message";
                            Map<String, Object> map = preGenParams();
                            map.put("fid", fid);
                            map.put("message", message);
                            String s = HttpClientUtils.sendPost(url, map);
                            JSONObject result = JSONObject.parseObject(s);
                            if (isOk(result)) {
                                System.out.println("你说 : " + message + "      " + DateUtils.formatDateTime(new Date()));
                            } else {
                                System.out.println(result.get("msg"));
                            }
                        }
                    }
                }
                mainViewListAction();
            }
        }).start();


    }

    public void addFriend(String fUsername){
        String url = getHttpPath() + "/apply/addfriend";
        Map<String, Object> map = preGenParams();
        map.put("friendusername",fUsername);
        String s = HttpClientUtils.sendPost(url, map);
        JSONObject result = JSONObject.parseObject(s);
        if(isOk(result)){
            System.out.println("申请添加好友成功,请等待对方通过");
        }else{
            System.out.println(result.get("msg"));
        }
    }

    public JSONObject getApplyFriendHistory(){
        String url = getHttpPath() + "/apply/lookmyapplyaddfriendlist";
        Map<String, Object> map = preGenParams();
        String s = HttpClientUtils.sendPost(url, map);
        JSONObject result = JSONObject.parseObject(s);
        if(isOk(result)){
            return result;
        }else {
            System.out.println(result.get("msg"));
            return null;
        }
    }


    public JSONArray getMyGroupListRequest(){
        String url=getHttpPath()+"/account/mygroups";
        Map<String, Object> map = preGenParams();
        String s = HttpClientUtils.sendPost(url, map);
        JSONObject result = JSONObject.parseObject(s);
        if (isOk(result)) {
            JSONArray groupList = result.getJSONArray("groupList");
            for(int i=0;i<groupList.size();i++){
                GlobalData.mapGroup.put(groupList.getJSONObject(i).getLong("groupId"),groupList.getJSONObject(i));
            }
            return groupList;
        }else {
            System.out.println(result.get("msg"));
            return null;
        }
    }

    public boolean registerRequest(String username, String pasword, String nickname, String phone){
        String url = getHttpPath() + "/account/register";
        Map<String, Object> map = preGenParams();
        map.put("username",username);
        map.put("password",pasword);
        map.put("nickname",nickname);
        map.put("phone",phone);
        String s = HttpClientUtils.sendPost(url, map);
        JSONObject result = JSONObject.parseObject(s);
        if (isOk(result)) {
            return true;
        }else {
            System.out.println(result.get("msg"));
            return false;
        }

    }


    public ArrayList<PersonMessageVo> getFriendChatMessageListRequest(Long fid) {
        String url = getHttpPath() + "/message/get_history_friend_message";
        Map<String, Object> map = preGenParams();
        map.put("fid", String.valueOf(fid));
        String s = HttpClientUtils.sendPost(url, map);
        JSONObject result = JSONObject.parseObject(s);
        if (isOk(result)) {
            ArrayList<PersonMessageVo> history_friend_message = result.getObject("history_friend_message", new TypeReference<ArrayList<PersonMessageVo>>() {
            });
            return history_friend_message;
        } else {
            System.out.println(result.get("msg"));
            return null;
        }
    }

    public ArrayList<MyFriendVo> getMyFriendListRequest() {
        String url = getHttpPath() + "/account/myfriends";
        Map<String, Object> map = preGenParams();
        map.put("isfirst", GlobalData.isFirst);
        String s = HttpClientUtils.sendPost(url, map);
        if(GlobalData.isFirst){
            GlobalData.isFirst=false;
        }
        JSONObject result = JSONObject.parseObject(s);
        if (isOk(result)) {
            ArrayList<MyFriendVo> myapplyaddfriendlist = result.getObject("friendlist", new TypeReference<ArrayList<MyFriendVo>>() {
            });
            for (MyFriendVo myFriendListVo : myapplyaddfriendlist) {
                GlobalData.mapMyFriend.put(myFriendListVo.getUid(), myFriendListVo);
            }
            return myapplyaddfriendlist;
        } else {
            System.out.println(result.get("msg"));
            return null;
        }
    }

}
